package graphs;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;

import error.GedivaException;

/**
 * class used to draw the pie chart
 * 
 * @author lindsaykubasik
 * 
 */
@SuppressWarnings("serial")
public class PieChart extends AbstractGraph<String, Double>
{

    /**
     * Constructor for PieChart
     */
    public PieChart()
    {
        myData = null;
        myLabels = null;
        myXvals = null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
     */
    public void paintComponent(Graphics pen)
    {
        int k = 0;
        Dimension bounds = getSize();
        if (myLabels.size() > 2)
            pen.drawString(myLabels.get(0) + "-" + myLabels.get(2),
                    (bounds.width / 2), 20);
        if (myLabels.size() > 0 && myLabels.size() <= 2)
            pen.drawString(myLabels.get(0), (bounds.width / 2), 20);
        Double total = 0.0;
        for (Object x : myXvals)
        {
            if (!(x instanceof String)
                    || !(myData.get(x).get(0) instanceof Double))
                throw new GedivaException("Improper data types.");

            if (myData.get(x).get(0) instanceof Double)
                total += (Double) myData.get(x).get(0);
        }
        int size;
        if (bounds.width < bounds.height)
        {
            size = bounds.width;
        }
        else
            size = bounds.height;

        double curValue = 0.0D;
        int startAngle = 0;
        int count = 0;
        for (Object x : myXvals)
        {
            startAngle = (int) (curValue * 360 / total);
            int arcAngle = (int) ((Double) myData.get(x).get(0) * 360 / total);
            if (count == myXvals.size() - 1)
            {
                arcAngle = 360 - startAngle;
            }
            count++;
            pen.setColor(randomColor());
            pen.fillArc(0, 0, size - 50, size - 50, startAngle, arcAngle);
            pen.drawString((String) x, bounds.width - 50, bounds.height
                    - (k * 15));
            curValue += (Double) myData.get(x).get(0);
            k++;
        }
        if (myLabels.get(1) != null)
            pen.setColor(Color.black);
        pen.drawString(myLabels.get(1), bounds.width - 50, bounds.height
                - (k * 15));
    }

    /*
     * (non-Javadoc)
     * 
     * @see graphs.AbstractGraph#toString()
     */
    public String toString()
    {
        return "PieChart";
    }
}
